import Taro, {Component} from '@tarojs/taro'
import {View, Button, Picker , Text , Image} from '@tarojs/components'
import {
  AtInput,
  AtTextarea,
  AtRadio,
  AtModal
} from 'taro-ui'


import CustomRadio from '../../component/CustomRadio/customRadio'

import DataManager from '../../utils/DataManager.js'

import './driverPost.scss'
import {base_url} from "../../network/config";
import arrowImage from '../../image/ic_arrow_right.png'
import questionIcon from '../../image/ic_question.png'


let isCommitEnable = true;
export default class PostPage extends Component {

  config = {
    navigationBarTitleText: '车找人'
  }

  onPullDownRefresh(){
    Taro.stopPullDownRefresh();
  }

  constructor(props) {
    super(props)

    this.releaseTimes = 0;
    this.type = 1
    this.state = {
      userName: '', peopleCount: '',
      startAddress: '', tagAddress: '', startDate: '', startTime: '',
      mobile: '', intro: '', agree: true, type: this.type, submit: true,
      loopPriceList:[],
      chosenLoop:'未选择自动发布',
      chosenLoopValue:'',
      chosenLoopCode:'',
      payWay:0, //   0微信支付  1积分支付
      integral:'',
      releaseTimes:'',//剩余发布次数,
      showLoopIntro:false
    }
  }

  componentDidMount() {

    this.setState({
      mobile : DataManager.getMobile()
    })

    this.loadDistinctList();
    this.loadUserDetail();

    this.auth = DataManager.getAuthInfo();
    let data = {platform: 'android_c', loginChannel: 'c', digest: DataManager.getAuthInfo().digest, type: this.type,};
    Object.assign(data, this.auth);

    let thiz = this
    Taro.request({
      url: 'https://www.vpin.top/a/stateless/car/userReleaseCount',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      dataType: 'json',
      data: data,
      success: (obj) => {
        let reps = obj.data
        thiz.releaseTimes = reps.data
        if (thiz.releaseTimes == 0) {
          thiz.setState({submit: thiz.releaseTimes == 0,  releaseTimes:thiz.releaseTimes})
        } else {
          thiz.setState({submit: thiz.releaseTimes == 0 , releaseTimes:thiz.releaseTimes})
        }

      },
      fail: (obj) => {
        Taro.showToast({
          title: '程序异常',
          icon: 'none',
          duration: 1000
        })

      }
    })
  }

  loadUserDetail(){
    let _this = this;

    let url = base_url + 'rest/user/userDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
      },
      method: 'GET',
      success(res) {
        console.log('userDetail=========' + JSON.stringify(res))
        if (res.data && res.data.data){
          _this.setState({
            integral : res.data.data.integral
          })
        }
      }
    })
  }

  loadDistinctList(){
    let _this = this;
    let url = base_url + 'stateless/dict/dictList'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        type:'car'
      },
      method: 'GET',
      success(res) {
        console.log('loop------------' + JSON.stringify(res))
        let loopList = [];
        if (res.data.data){
          loopList = loopList.concat(res.data.data);
        }
        _this.setState({
          loopPriceList:loopList,
        })
      }
    })
  }

  handleFromChange(value) {
    this.setState({startAddress: value})
  }

  handleToChange(value) {
    this.setState({tagAddress: value})
  }

  handleWhenChange(value) {
    let val = value.detail.value;
    this.setState({startDate: val})
  }

  handleTimeChange(value) {

    this.setState({startTime: value.detail.value + ":00"})
  }

  handleMenChange(value) {
    this.setState({peopleCount: value})
  }

  handleContactChange(value) {
    this.setState({userName: value})
  }

  handlePhoneChange(value) {
    this.setState({mobile: value})
  }

  handleMemoChange(event) {
    this.setState({intro: event.target.value})
  }

  handleAgree() {
    let flag = this.state.agree
    if (this.releaseTimes == 0) {
      this.setState({agree: !flag, submit: true})
      return
    }
    this.setState({agree: !flag, submit: flag})
  }

  handleShowProtocol() {
    Taro.navigateTo({
      url:'/pages/protocol/driverProtocol'
    });
  }

  commitParamsCheck(){
    let checked = false;
    let hint = '';
    if (!this.state.startAddress){
      hint = '请填写出发地'
    } else if (!this.state.tagAddress){
      hint = '请填写目的地'
    } else if (!this.state.startDate) {
      hint = '请选择出发日期'
    } else if (!this.state.startTime){
      hint = '请选择出发时间'
    } else if (!this.state.peopleCount){
      hint = '请填写可乘人数'
    } else if (!this.state.userName){
      hint = '请填写联系人'
    } else if (!this.state.mobile){
      hint = '请填写您的手机号'
    } else {
      checked = true;
    }
    if (!checked){
      Taro.showToast({
        title:hint,
        icon:'none'
      })
    }

    return checked;
  }

  handleOnSubmit() {

    if (!isCommitEnable){
      return;
    }

    if (!this.commitParamsCheck()){
      return;
    }

    isCommitEnable = false;

    if (this.state.chosenLoopValue && this.state.chosenLoopValue > 0 && this.state.payWay == 0){ // 先支付
      this.onPayForPost();
    } else {
      this.onCarPost();
    }
  }

  onPayForPost(){
    let _this = this;
    Taro.request({
      url:base_url + 'rest/order/createOrder',
      data:{
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'wechat',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        openId:DataManager.getOpenId(),
        amount:this.state.chosenLoopValue,
      },
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      success: (obj) => {
        if (obj.data.status == 'success') {
          if (obj.data.data){
            let timeStamp = obj.data.data.timeStamp;
            let nonceStr = obj.data.data.nonceStr;
            let payPackage = obj.data.data.package;
            let signType = obj.data.data.signType;
            let paySign = obj.data.data.paySign;

            Taro.requestPayment({
              'timeStamp': timeStamp,
              'nonceStr': nonceStr,
              'package': payPackage,
              'signType': signType,
              'paySign': paySign,
              success(res){
                _this.onCarPost();
              },
              fail(res){
                Taro.showToast({
                  title:'支付失败',
                  icon:'none'
                })
                console.log('pay--failed----' + JSON.stringify(res))
                isCommitEnable = true;
              }
            })
          }
        } else {
          Taro.showToast({
            title: obj.data.message,
            icon: 'none',
            duration: 1000
          })
          isCommitEnable = true;
        }
      },
      fail(obj){
        Taro.showToast({
          title: '支付失败',
          icon: 'none',
          duration: 1000
        })
        isCommitEnable = true;
      }
    })
  }

  onCarPost (){
    let data = {
      platform: 'android_c',
      loginChannel: 'c',
      userName: this.state.userName,
      mobile: this.state.mobile,
      startDate: this.state.startDate + " " + this.state.startTime,
      peopleCount: this.state.peopleCount,
      type: this.type,
      startAddress: this.state.startAddress,
      tagAddress: this.state.tagAddress,
      intro: this.state.intro,
      code : this.state.chosenLoopCode,
      payType : this.state.payWay,
    };
    Object.assign(data, this.auth);

    Taro.request({
      url: 'https://www.vpin.top/a/rest/car/applyCar',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      dataType: 'json',
      data: data,
      success(obj){
        if (obj.data.status == 'fail') {
          Taro.showToast({
            title: '发布失败',
            icon: 'none',
            duration: 1000
          })
        } else {
          Taro.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 1000
          })
          Taro.eventCenter.trigger('driverPost' ,[]);
          Taro.navigateBack({delta: 1});
        }
        isCommitEnable = true;
      },
      fail(obj){
        Taro.showToast({
          title: '程序异常',
          icon: 'none',
          duration: 1000
        })
        isCommitEnable = true;
      }
    })
  }

  handlePayWayChange = (value) =>{
    this.setState({
      payWay:value,
    })
  }

  onLoopSelect = (e) =>{
    console.log('loopSelect--------' + JSON.stringify(e))
    if (this.state.integral < this.state.loopPriceList[e.detail.value].value) {
      this.setState({
        chosenLoop: this.state.loopPriceList[e.detail.value].name,
        chosenLoopValue:this.state.loopPriceList[e.detail.value].value,
        chosenLoopCode:this.state.loopPriceList[e.detail.value].code,
        payWay:0
      })
    } else {
      this.setState({
        chosenLoop: this.state.loopPriceList[e.detail.value].name,
        chosenLoopValue:this.state.loopPriceList[e.detail.value].value,
        chosenLoopCode:this.state.loopPriceList[e.detail.value].code
      })
    }
  }

  onLoopCancel = () =>{
    this.setState({
      chosenLoop: '未选择自动发布',
      chosenLoopValue:'',
      chosenLoopCode:'',
    })
  }

  onIntroShow = (e) =>{
    this.setState({showLoopIntro : true})
    e.stopPropagation()  // 拦截事件冒泡
  }

  onIntroHide = () =>{
    this.setState({showLoopIntro : false})
  }

  render() {

    let nowDate = new Date()
    let start = nowDate.getFullYear() + '-' + nowDate.getMonth() + "-" + nowDate.getDay()

    let startDateShow = this.state.startDate ? this.state.startDate : '点击选择出发日期';
    let startTimeShow = this.state.startTime ? this.state.startTime : '点击选择出发时间';

    let dateTextStyle = this.state.startDate ? 'date-input-text' : 'date-input-text-hint';
    let timeTextStyle = this.state.startTime ? 'date-input-text' : 'date-input-text-hint';

    let weiPay = {label: '微信支付', value: 0};
    let scoreLabel = '积分支付' + ' （剩余积分：' + this.state.integral + '）'
    let scoreDisable = this.state.integral < this.state.chosenLoopValue * 10;
    let scorePay = {label:scoreLabel , value: 1 , disabled : scoreDisable};
    let payWayList = [weiPay , scorePay];

    let commitValue = '提交'
    if (this.releaseTimes == 0){
      commitValue = '今日发布次数已用完';
    } else {
      if (this.state.chosenLoopValue){
        if (this.state.payWay == 0) {
          commitValue= '需支付 ¥ ' + this.state.chosenLoopValue + '元';
        } else if (this.state.payWay == 1){
          commitValue= '需支付 ' + this.state.chosenLoopValue * 10 + '积分';
        }
      }
    }
    return (

      <View>
        <View style='padding:0px 5px'>
          <AtInput
            name='from'
            className='common-input'
            value={this.state.startAddress}
            clear
            title='出发地'
            type='text'
            placeholder='请填写出发地'
            border
            maxlength={50}
            onChange={this.handleFromChange.bind(this)}/>
          <AtInput
            name='to'
            className='common-input'
            value={this.state.tagAddress}
            clear
            title='目的地'
            type='text'
            placeholder='请填写目的地'
            maxlength={50}
            onChange={this.handleToChange.bind(this)}/>

          <Picker mode='date' value='YYYY-MM-DD' start={start} onChange={this.handleWhenChange.bind(this)}>
            <View className='date-input-container'>
              <Text className='date-input-text'>出发日期</Text>
              <Text className={dateTextStyle}>{startDateShow}</Text>
            </View>
          </Picker>
          <View className='date-divider'></View>
          <Picker mode='time' onChange={this.handleTimeChange.bind(this)}>
            <View className='date-input-container'>
              <Text className='date-input-text'>出发时间</Text>
              <Text className={timeTextStyle}>{startTimeShow}</Text>
            </View>
          </Picker>
          <View className='date-divider'></View>
          <AtInput
            className='common-input'
            name='men'
            clear
            title='可乘人数'
            value={this.state.peopleCount}
            type='number'
            placeholder='请填写可乘人数'
            onChange={this.handleMenChange.bind(this)}/>
          <AtInput
            className='common-input'
            name='contact'
            value={this.state.userName}
            clear
            title='联系人'
            type='text'
            maxlength='10'
            placeholder='请填写联系人'
            onChange={this.handleContactChange.bind(this)}/>
          <AtInput
            className='common-input'
            name='phone'
            value={this.state.mobile}
            clear
            title='手机号'
            type='phone'
            placeholder='请输入您的手机号'
            onChange={this.handlePhoneChange.bind(this)}/>

          <Picker
            mode='selector'
            range={this.state.loopPriceList}
            rangeKey='name'
            value='0'
            onChange={this.onLoopSelect.bind(this)}
            onCancel={this.onLoopCancel.bind(this)}
          >
            <View className='driver-post-top-container'>
              <View className='driver-post-hint'>
                <Text className='driver-post-top-text'>是否自动发布</Text>
                <Image style='width:19px;height:19px;margin-left:5px' src={questionIcon} onClick={this.onIntroShow.bind(this)}/>
              </View>
              <View className='driver-post-top-right'>
                <Text className='driver-post-top-text'>{this.state.chosenLoop}</Text>
                <Image className='driver-post-top-arrow' src={arrowImage}/>
              </View>
            </View>
          </Picker>
          <View className='date-divider'></View>

          {this.state.chosenLoopValue && <AtRadio
            options={payWayList}
            value={this.state.payWay}
            onClick={this.handlePayWayChange.bind(this)}
          />}
          <View className='memo'>备注</View>

          <View style='margin-bottom:2px'>
            <AtTextarea value={this.state.intro} onChange={this.handleMemoChange.bind(this)} placeholder='' maxlength='100' />
          </View>
        </View>

        <View className='disclaimer'>
          <CustomRadio checked={this.state.agree} onClick={this.handleAgree.bind(this)}/>
          <View className='protocol-ele' onClick={this.handleShowProtocol.bind(this)}>我已阅读并同意《拼车平台声明》</View>
        </View>

        <View className='post-section'>
          <Button className='btn-post' disabled={this.state.submit} onClick={this.handleOnSubmit.bind(this)}>{commitValue}</Button>
        </View>

        <AtModal
          isOpened={this.state.showLoopIntro}
          title='自动发布'
          confirmText='确认'
          onClose={this.onIntroHide.bind(this)}
          onConfirm={this.onIntroHide.bind(this)}
          content='每天23点自动发布下一天的相同的本信息！'
        />

      </View>


    )


  }

}
